//
//  MTClubActivitiesViewController.swift
//  MT
//
//  Created by ooops on 2019/12/26.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit

import MTCategory
import RxSwift
import RxCocoa
import ObjectMapper
import Result

class MTClubActivitiesViewController: BaseViewController {

    private lazy var provider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private var clubId: String?
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    private var loadType: Int = 1
    
    private var activities: [MTClubActivitModel] = []
    
    override func refreshView() {
        loadFirst()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "全部活动"
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.theme.background
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadFirst()
        
        tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        tableView.setContentOffset(CGPoint(x: 0, y: -20), animated: false)
        
        tableView.mj_header?.ignoredScrollViewContentInsetTop = 30
        tableView.mj_footer?.ignoredScrollViewContentInsetBottom = -20
    }
    
    convenience init(clubId: String?) {
        self.init()
        self.clubId = clubId
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        loadEndActivities(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadEndActivities(loadMore: true)
        
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    private func loadEndActivities(loadMore: Bool) {
        guard let gid = clubId else { return }
        
        let queryParam: [String : Any] = ["id" : gid, "curPage" : currentPage, "pageSize" : pageSize]
        MTClubTool.queryClubActivities(provider: provider, requestParam: queryParam, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_footer?.endRefreshing()
            weakSelf.tableView.mj_header?.endRefreshing()
            if weakSelf.currentPage == 1 {
                weakSelf.tableView.mj_footer?.state = .idle
            }
            
            if let m = model {
                debugPrint("message: ", m.message ?? "")
                if let r = m.result {
                    if (m.page?.pages == m.page?.curPage) {
                        weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                    if loadMore == true {
                        weakSelf.activities = weakSelf.activities + r
                    } else {
                        weakSelf.activities = r
                    }
                    
                    weakSelf.hiddenHF(isHidden: weakSelf.activities.count == 0)
                } else {
                    weakSelf.hiddenHF(isHidden: true)
                }
                
                DispatchQueue.main.async {
                    weakSelf.tableView.reloadData()
                }
            }
            
        }) { (error) in
            
        }
        
        
//        let a: Observable<MTRequestResult<MTClubActivitiesModel>> = provider.rx.requestResult(.queryEnrollRun(["pushId" : gid]))
//        let b: Observable<MTRequestResult<MTClubActivitiesModel>> = provider.rx.requestResult(.queryEnrollRun(["pushId" : gid]))
//        Observable.zip(a, b).subscribe { [weak self] (element) in
//            guard let weakSelf = self else { return }
//            if let el1: MTRequestResult<MTClubActivitiesModel> = element.element?.0 {
//
//                if let modelRnu = el1.result.value, let r1 = modelRnu.result {
//                    weakSelf.activities += r1
//                }
//
//                weakSelf.tableView.reloadData()
//            }
//
//            if let el2: MTRequestResult<MTClubActivitiesModel> = element.element?.1 {
//
//                if let modelEnd = el2.result.value, let r2 = modelEnd.result {
//                    weakSelf.activities += r2
//                }
//
//                weakSelf.tableView.reloadData()
//            }
//
//        }.disposed(by: globalDisposedBag)
        
    }
    //Event<(MTRequestResult<MTClubActivitiesModel>, MTRequestResult<MTClubActivitiesModel>)>
    //(result:Result<MTClubActivitiesModel, AnyError> , isCache:Bool)
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTClubActivitiesViewCell.self, forCellReuseIdentifier: MTClubActivitiesViewCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor.theme.background
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.emptySetView = ViewFactory.emptySetView { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadFirst()
        }
        return table
    }()
    
    
}

extension MTClubActivitiesViewController: UITableViewDelegate, UITableViewDataSource {
    
    //MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.activities.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTClubActivitiesViewCell.reuseIdentity(), for: indexPath) as! MTClubActivitiesViewCell
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTClubActivitiesViewCell, forRowAt indexPath: IndexPath) {
        let model: MTClubActivitModel = self.activities[indexPath.row]
        
        cell.model = model
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let gid = clubId else { return }
        let model: MTClubActivitModel = self.activities[indexPath.row]
        
        /// 是否活动已结束
        if model.activityStatus == 2 || model.activityStatus == 3 {
            MBProgressHUD_JChat.show(text: "活动已结束", view: self.view)
            return
        }
        
        if model.enrollNum == model.num {
            MBProgressHUD_JChat.show(text: "活动人数已满", view: self.view)
            return
        }
        
        JMSGGroup.groupInfo(withGroupId: gid, completionHandler: { (result, error) in
            if error == nil, let g = result as? JMSGGroup, let activityId = model.id {
                //let vc = MTClubActiviteDetailViewController(group: g, isEditMode: false, activityId: "\(activityId)"
                let vc = MTClubActiviteDetailViewController(group: g, isEditMode: false, activityId: "\(activityId)") { [weak self] (activityId) in
                    guard let weakSelf = self else { return }
                    model.joined = true
                    model.enrollNum += 1
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
        })
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
